﻿using System.Text;
using Newtonsoft.Json;
using System.Net.Http;
using System;
using Newtonsoft.Json.Linq;

namespace YookingBizYQ.Class.Public
{
    public class clsWxOffical
    {
        public static readonly string appId = "wxdeebb03b559fd758";
        public static readonly string appSecret = "70a62b735a3012c944ab5b351939a048";
        public static readonly string sendTemplateUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}";

        // 推送微信模板消息
        public  static void SendTemplateMessageAsync(string openId, string templateId, object data, string tzUrl)
        {
            string accessToken = GetAccessToken();
            string url = string.Format(sendTemplateUrl, accessToken);

            var requestBody = new
            {
                touser = openId,
                template_id = templateId,
                url = tzUrl, // 可选，点击模板消息跳转链接  
                data = data
            };
            // 参数序列化
            string json = JsonConvert.SerializeObject(requestBody);
            

            using (HttpClient client = new HttpClient())
            {
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response = client.PostAsync(url, content).Result; // 同步获取结果  
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result; // 同步获取结果
                Console.WriteLine(responseBody); // 可选地记录响应
            }
        }
        // 获取token
        public static string GetAccessToken()
        {
            string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = client.GetAsync(url).Result; // 同步获取结果  
                response.EnsureSuccessStatusCode();
                string responseBody = response.Content.ReadAsStringAsync().Result; // 同步获取结果  
                JObject json = JObject.Parse(responseBody);
                return json["access_token"].ToString();
            }
        }
    }
}
